import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../../../core/widgets/app_state_widget.dart';
import '../../../../core/widgets/app_shimmer.dart';
import '../controllers/example_list_controller.dart';
import '../models/example_item.dart';

class ExampleListPage extends StatelessWidget {
  const ExampleListPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ExampleListController>(
      init: ExampleListController(),
      builder: (controller) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('列表示例'),
            actions: [
              IconButton(
                icon: const Icon(Icons.search),
                onPressed: () => _showSearchDialog(context, controller),
              ),
              IconButton(
                icon: const Icon(Icons.filter_list),
                onPressed: () => _showFilterDialog(context, controller),
              ),
            ],
          ),
          body: Obx(() => AppStateWidget(
            viewState: controller.viewState,
            onRetry: controller.onRetry,
            child: Column(
              children: [
                // 搜索栏
                if (controller.searchKeyword.isNotEmpty)
                  Container(
                    padding: EdgeInsets.all(16.w),
                    color: Theme.of(context).colorScheme.surface,
                    child: Row(
                      children: [
                        Icon(
                          Icons.search,
                          size: 16.w,
                          color: Theme.of(context).colorScheme.onSurface,
                        ),
                        SizedBox(width: 8.w),
                        Expanded(
                          child: Text(
                            '搜索: ${controller.searchKeyword}',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Theme.of(context).colorScheme.onSurface,
                            ),
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: controller.clearSearch,
                          iconSize: 20.w,
                        ),
                      ],
                    ),
                  ),
                
                // 列表
                Expanded(
                  child: SmartRefresher(
                    controller: controller.refreshController,
                    enablePullDown: true,
                    enablePullUp: true,
                    onRefresh: controller.onRefresh,
                    onLoading: controller.onLoadMore,
                    child: Obx(() => ListView.separated(
                      padding: EdgeInsets.all(16.w),
                      itemCount: controller.items.length,
                      separatorBuilder: (context, index) => SizedBox(height: 16.h),
                      itemBuilder: (context, index) {
                        final item = controller.items[index];
                        return _buildListItem(context, item, index, controller);
                      },
                    )),
                  ),
                ),
              ],
            ),
          )),
        );
      },
    );
  }

  Widget _buildListItem(
    BuildContext context,
    ExampleItem item,
    int index,
    ExampleListController controller,
  ) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: InkWell(
        onTap: () => _showItemDetail(context, item),
        borderRadius: BorderRadius.circular(12.r),
        child: Padding(
          padding: EdgeInsets.all(16.w),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 图片
              ClipRRect(
                borderRadius: BorderRadius.circular(8.r),
                child: CachedNetworkImage(
                  imageUrl: item.imageUrl,
                  width: 60.w,
                  height: 60.w,
                  fit: BoxFit.cover,
                  placeholder: (context, url) => AppShimmer(
                    width: 60.w,
                    height: 60.w,
                  ),
                  errorWidget: (context, url, error) => Container(
                    width: 60.w,
                    height: 60.w,
                    color: Colors.grey[300],
                    child: const Icon(Icons.error),
                  ),
                ),
              ),
              SizedBox(width: 16.w),
              
              // 内容
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            item.title,
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 8.w,
                            vertical: 4.h,
                          ),
                          decoration: BoxDecoration(
                            color: item.isActive ? Colors.green : Colors.grey,
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: Text(
                            item.isActive ? '活跃' : '非活跃',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      item.description,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[600],
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        Icon(
                          Icons.access_time,
                          size: 14.w,
                          color: Colors.grey[500],
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          _formatDate(item.createdAt),
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[500],
                          ),
                        ),
                        const Spacer(),
                        PopupMenuButton<String>(
                          onSelected: (value) {
                            switch (value) {
                              case 'toggle':
                                controller.toggleItemStatus(index);
                                break;
                              case 'delete':
                                _showDeleteDialog(context, index, controller);
                                break;
                            }
                          },
                          itemBuilder: (context) => [
                            PopupMenuItem(
                              value: 'toggle',
                              child: Row(
                                children: [
                                  Icon(item.isActive ? Icons.pause : Icons.play_arrow),
                                  SizedBox(width: 8.w),
                                  Text(item.isActive ? '设为非活跃' : '设为活跃'),
                                ],
                              ),
                            ),
                            const PopupMenuItem(
                              value: 'delete',
                              child: Row(
                                children: [
                                  Icon(Icons.delete, color: Colors.red),
                                  SizedBox(width: 8),
                                  Text('删除', style: TextStyle(color: Colors.red)),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _showSearchDialog(BuildContext context, ExampleListController controller) {
    final searchController = TextEditingController(text: controller.searchKeyword);
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索'),
        content: TextField(
          controller: searchController,
          decoration: const InputDecoration(
            hintText: '输入搜索关键词',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              controller.search(searchController.text);
              Navigator.pop(context);
            },
            child: const Text('搜索'),
          ),
        ],
      ),
    );
  }

  void _showFilterDialog(BuildContext context, ExampleListController controller) {
    bool? activeFilter = controller.filterParams['isActive'];
    String sortBy = controller.sortBy;
    String sortOrder = controller.sortOrder;
    
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('筛选和排序'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('状态筛选:'),
              RadioListTile<bool?>(
                title: const Text('全部'),
                value: null,
                groupValue: activeFilter,
                onChanged: (value) => setState(() => activeFilter = value),
              ),
              RadioListTile<bool?>(
                title: const Text('活跃'),
                value: true,
                groupValue: activeFilter,
                onChanged: (value) => setState(() => activeFilter = value),
              ),
              RadioListTile<bool?>(
                title: const Text('非活跃'),
                value: false,
                groupValue: activeFilter,
                onChanged: (value) => setState(() => activeFilter = value),
              ),
              const SizedBox(height: 16),
              const Text('排序方式:'),
              DropdownButton<String>(
                value: sortBy.isEmpty ? 'id' : sortBy,
                items: const [
                  DropdownMenuItem(value: 'id', child: Text('ID')),
                  DropdownMenuItem(value: 'title', child: Text('标题')),
                  DropdownMenuItem(value: 'createdAt', child: Text('创建时间')),
                ],
                onChanged: (value) => setState(() => sortBy = value ?? 'id'),
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  const Text('排序顺序:'),
                  const SizedBox(width: 16),
                  DropdownButton<String>(
                    value: sortOrder,
                    items: const [
                      DropdownMenuItem(value: 'asc', child: Text('升序')),
                      DropdownMenuItem(value: 'desc', child: Text('降序')),
                    ],
                    onChanged: (value) => setState(() => sortOrder = value ?? 'desc'),
                  ),
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                controller.clearFilters();
                controller.clearSort();
                Navigator.pop(context);
              },
              child: const Text('清除'),
            ),
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (activeFilter != null) {
                  controller.setFilter({'isActive': activeFilter});
                } else {
                  controller.clearFilters();
                }
                controller.setSort(sortBy, sortOrder: sortOrder);
                Navigator.pop(context);
              },
              child: const Text('应用'),
            ),
          ],
        ),
      ),
    );
  }

  void _showItemDetail(BuildContext context, ExampleItem item) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(item.title),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8.r),
              child: CachedNetworkImage(
                imageUrl: item.imageUrl,
                width: double.infinity,
                height: 200.h,
                fit: BoxFit.cover,
              ),
            ),
            SizedBox(height: 16.h),
            Text('描述: ${item.description}'),
            SizedBox(height: 8.h),
            Text('状态: ${item.isActive ? '活跃' : '非活跃'}'),
            SizedBox(height: 8.h),
            Text('创建时间: ${_formatDate(item.createdAt)}'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  void _showDeleteDialog(BuildContext context, int index, ExampleListController controller) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个项目吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              controller.deleteItem(index);
              Navigator.pop(context);
            },
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}